package cn.haocxy.jfm.gui;

import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import cn.haocxy.jfm.file.FilePath;
import cn.haocxy.jfm.filelist.FileList;
import cn.haocxy.jfm.filelist.SortByName;
import cn.haocxy.jfm.util.Executor;

public final class JfmPane {
	
	private final BorderPane root = new BorderPane();
	
	private final FileList model;
	
	private final FileListPane fileListPane;
	
	private final AnchorPane infoPane = new AnchorPane();
	
	private final Text info = new Text();
	
	private long lastInfoTime = 0;
	
	public JfmPane(FileList model) {
		this.model = model;
		fileListPane = new FileListPane(model, new SortByName());
		
		root.setTop(new TopArea(model).toNode());
		root.setCenter(fileListPane.toNode());
		root.setBottom(infoPane);
		
		init();
	}
	
	public JfmPane(FilePath path) {
		model = new FileList(path);
		fileListPane = new FileListPane(model, new SortByName());
		
		root.setTop(new TopArea(model).toNode());
		root.setCenter(fileListPane.toNode());
		root.setBottom(infoPane);
		
		init();
	}
	
	public JfmPane(String path) {
		model = new FileList(path);
		fileListPane = new FileListPane(model, new SortByName());
		root.setCenter(fileListPane.toNode());
		
		TopArea top = new TopArea(model);
		root.setTop(top.toNode());
		
		init();
	}
	
	private void init() {
		root.setPrefSize(800.0, 600.0);
		
		infoPane.getChildren().add(info);
		AnchorPane.setTopAnchor(info, 5.0);
		AnchorPane.setBottomAnchor(info, 5.0);
		AnchorPane.setLeftAnchor(info, 5.0);
		
		BackgroundFill fill = new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY);
		Background bg = new Background(fill);
		infoPane.setBackground(bg);
		
		fileListPane.setOnInfo(info->{
			lastInfoTime = System.currentTimeMillis();
			setInfo(Color.BLACK, info);
			
			// 5s后自动清空显示的信息 , 以免使用户以为问题还在
			Executor.delayui(5000, new Runnable() {
				
				private final long time = lastInfoTime;
				
				@Override
				public void run() {
					
					// 如果在这期间有更新 , 则不清空
					if (time < lastInfoTime) {
						return;
					}
					clearInfo();
				}
			});
			
		});
	}
	
	public void setInfo(Color color, String info) {
		this.info.setFill(color);
		this.info.setText(info);
	}
	
	public void clearInfo() {
		info.setText("");
	}
	
	public void onShowing() {
		fileListPane.toNode().requestFocus();
	}
	
	public Parent toNode() {
		return root;
	}
}
